#!/usr/bin/env python3
# vim: tabstop=4 shiftwidth=4 expandtab

import gemtextparser
import argparse
import sys

if __name__ == "__main__":

    argparser = argparse.ArgumentParser(prog="gemtextparser",description="A library and CLI tool for parsing and validating gemtext (mimetype text/gemini) in python3.")
    argparser.add_argument("-f","--file",help="File to validate")
    args = argparser.parse_args()

    if not args.file:
        sys.stderr.buffer.write(b"Nothing to do.\n")
        exit()

    gp = gemtextparser.GemtextParser()

    gemtextlines = gp.parseText(open(args.file, "r").read())

    # Validating
    errors = 0
    lastpreformstart = None
    for index, line in enumerate(gemtextlines):
        try:
            if not line.text() and line.linetype not in [gemtextparser.LineType.PLAIN, gemtextparser.LineType.PREFORM]:
                print(f"ERROR: Line {index} with linetype '{line.linetype.name}' has no actual content.")
                errors+=1
        except:
            print(f"ERROR: Line {index} with linetype '{line.linetype.name}' does not validate.")
            errors+=1
    if gp.preformMode:
        print("ERROR: Unclosed preformatted block.")
        errors+=1

    print(f"\nFile '{args.file}' validated. Errors found: {str(errors)}")

